package com.binvshe.binvshe.common.web;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.support.annotation.Keep;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.alipay.sdk.app.PayTask;
import com.binvshe.binvshe.account.ui.LoginActivity;
import com.binvshe.binvshe.common.pay.AlipayHandler;
import com.binvshe.binvshe.common.pay.PayReceiver;
import com.binvshe.binvshe.common.pay.PayReceiverFail;
import com.binvshe.binvshe.common.pay.PayResultCallback;
import com.binvshe.binvshe.wxapi.WXPayEntryActivity;
import com.cncn.youmengsharelib.ShareData;
import com.pachong.android.frameworkbase.utils.AppUtil;
import com.pachong.android.frameworkbase.utils.NetUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/7/28
 * 移动端接口的实现类
 */
public class MobileFunImpl implements MobileImpable {

    private CommonWebviewFragment mFragment;
    private IWXAPI msgApi;
    private PayTask alipay;
    private PayReceiver payReceiver;
    private PayReceiverFail payReceiverFail;


    public MobileFunImpl(CommonWebviewFragment fragment) {
        mFragment = fragment;
        initPay();
    }

    private void initPay() {
        msgApi = WXAPIFactory.createWXAPI(getContext(), null);
        //将该app注册到微信
        String wetharAppid = WXPayEntryActivity.WETHAR_APPID;
        msgApi.registerApp(wetharAppid);
        alipay = new PayTask(mFragment.getActivity());

        //支付成功的回调
        payReceiver = new PayReceiver(new PayResultCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFail() {

            }
        });
        getContext().registerReceiver(payReceiver, new IntentFilter(WXPayEntryActivity.WECHAR_PAY));

        //支付失败的回调
        payReceiverFail = new PayReceiverFail(new PayResultCallback() {
            @Override
            public void onSuccess() {
                mFragment.getWebview().loadUrl("javascript:onPaySuccess(1)");
            }

            @Override
            public void onFail() {
                mFragment.getWebview().loadUrl("javascript:onPaySuccess(0)");
            }
        });
        getContext().registerReceiver(payReceiverFail, new IntentFilter(WXPayEntryActivity.WECHAR_PAY_FAIL));

    }
    //上下文
    private Context getContext() {
        return mFragment.getContext();
    }


    //web调支付

    /**
     * 支付 paytype : 0表示支付宝，1表示微信支付
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public void pay(String config){
        Log.e("准备支付", "web use pay" + config);
        try {
            JSONObject jsonObject = new JSONObject(config);
            String type = jsonObject.getString("type");
            //微信支付
            if(type.equals("wxpay")){
                String params = jsonObject.getString("params");
                onStartWechatPay(params);
            }else{
                String params = jsonObject.getString("params");
                startAliPay(params);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    private void startAliPay(final String params) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                // 调用支付接口，获取支付结果
                String result = alipay.pay(params);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                alipayHanlder.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 调用阿里支付
     */
    private AlipayHandler alipayHanlder = new AlipayHandler(new PayResultCallback(){

        @Override
        public void onSuccess() {
            mFragment.getWebview().loadUrl("javascript:onPaySuccess(0)");
        }

        @Override
        public void onFail() {
            mFragment.getWebview().loadUrl("javascript:onPaySuccess(1)");
        }
    });//启动阿里支付回调的handle

    private void onStartWechatPay(String params) {
        //调用微信支付
        try {
            JSONObject jsonObject = new JSONObject(params);
            PayReq request = new PayReq();
            //微信分配的公众账号ID
            request.appId = jsonObject.getString("appid");
            //微信支付分配的商户号
            request.partnerId = jsonObject.getString("partnerid");
            //微信返回的支付交易会话ID
            request.prepayId = jsonObject.getString("prepayid");
            //暂填写固定值Sign=WXPay
            request.packageValue = jsonObject.getString("package");
            //随机字符串，不长于32位。推荐随机数生成算法
            request.nonceStr = jsonObject.getString("noncestr");
            //时间戳，请见接口规则-参数规定
            request.timeStamp = jsonObject.getString("timestamp");
            //签名，详见签名生成算法
            request.sign = jsonObject.getString("sign");
            msgApi.sendReq(request);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        }


    @Keep
    @JavascriptInterface
    @Override
    public String getTokenInfo() {
        String token = null;
       /* if (AccountManager.isTokenValid()) {
            TokenInfo tokenInfo = AccountManager.getTokenInfo();
            token = GsonUtils.toJson(tokenInfo);
        }*/
        return token;
    }
    @Keep
    @JavascriptInterface
    @Override
    public void goLogin() {
        LoginActivity.start(mFragment.getActivity());
    }

    @Keep
    @JavascriptInterface
    @Override
    public void uploadImage(String tag) {
        Log.d("kyluzoi", "web use uploadimage");
        /*PhotoAlertFragment photoAlertFragment = new PhotoAlertFragment();
        photoAlertFragment.show(getActivity().getFragmentManager(), "tag");
        photoAlertFragment.setOnClickable(this);
        mSynTag = tag;*/
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showToast(String url) {
//        return mConnectable.callback();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void share(String title, String content, String imgUrl, String targetUrl) {
        Log.d("kyluzoi", "web use share");
        ShareData shareInfo = new ShareData(imgUrl, title, content, targetUrl);
        if (TextUtils.isEmpty(shareInfo.getImageUrl())) {
            shareInfo.setImageUrl("http://baidu.com");
        }
//      ShareHelper.share(getActivity(), MySharePlatformActivity.class, shareInfo, new MyShareListener());
//        ShareHelper.share(getActivity(), MySharePlatformActivity.class, shareInfo, new MyShareListener());
    }

    @Keep
    @JavascriptInterface
    @Override
    public void back() {
        mFragment.getActivity().finish();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public void hideTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public boolean netIsAvalible() {
        return NetUtil.isAvalible(mFragment.getActivity());
    }

    @Keep
    @JavascriptInterface
    @Override
    public int getVersionCode() {
        return AppUtil.getVersionCode(mFragment.getActivity());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }
}
